<script lang="ts" setup>
  import '@wangeditor/editor/dist/css/style.css';
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
  import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from 'vue';

  const props = defineProps<{
    modelValue?: string;
    placeholder?: string;
  }>();

  const emit = defineEmits(['update:modelValue']);

  const editorRef = shallowRef();
  // @ts-ignore
  const handleCreated = (editor) => {
    editorRef.value = editor;
    if (editorRef.value) {
      // @ts-ignore
      editorRef.value.setHtml(props.modelValue || '');
    }
  };
  const editorConfig = {
    placeholder: props.placeholder || '请输入',
    MENU_CONF: {
      uploadImage: {
        server: '/golf/api/v1/common/image/upload',
        fieldName: 'upload',
        headers: {
          token: localStorage.getItem('token'),
        },
        // @ts-ignore
        customInsert: async (a, b) => {
          // @ts-ignore
          if (a.data) {
            // @ts-ignore
            b(a.data);
          }
        },
      },
    },
  };
  const toolbarConfig = {
    excludeKeys: [
      'code',
      'sub',
      'sup',
      'fontFamily',
      'insertImage',
      'deleteImage',
      'editImage',
      'viewImageLink',
      'imageWidth30',
      'imageWidth50',
      'imageWidth100',
      'emotion',
      'insertLink',
      'editLink',
      'unLink',
      'viewLink',
      'codeBlock',
      'blockquote',
      'fullScreen',
      'insertVideo',
      'uploadVideo',
      'editVideoSize',
      'codeSelectLang',
    ],
  };
  const value = ref('');

  onMounted(() => {
    value.value = props.modelValue || '';
    if (editorRef.value) {
      // @ts-ignore
      editorRef.value.setHtml(value.value);
    }
  });

  watch([value], () => {
    emit('update:modelValue', value.value);
  });

  onBeforeUnmount(() => {
    if (editorRef.value) {
      // @ts-ignore
      editorRef.value.destroy();
    }
  });
</script>

<template>
  <div style="border: 1px solid var(--color-neutral-3)">
    <Toolbar
      :editor="editorRef"
      :default-config="toolbarConfig"
      mode="default"
      style="border-bottom: 1px solid var(--color-neutral-3)"
    />

    <Editor
      v-model="value"
      mode="default"
      :default-config="editorConfig"
      style="min-height: 600px"
      @on-created="handleCreated"
    />
  </div>
</template>
